<template>
    <div class="qrcode_container" :style="containerStyle">
        <template v-for="(item, index) in dataList">
            <div class="qrcode_item" :key="index" :style="itemStyle">
                <div class="qrcode_img" :ref="`qrcode_${item.sid}`"></div>
                <span class="tip_msg" :style="tipStyle" v-if="item.tip">{{ item.tip }}</span>
            </div>
        </template>
    </div>
</template>

<script>
import QRCode from 'qrcodejs2';
import { hiprint } from "@common/plugins/hiprint";

export default {
    name: "QrCode",
    props: {
        data: {
            type: Array,
            default: null,
        },
        pageSize: {
            type: String,
            default: null,
        },
        size: {
            type: Number,
            default: 240,
        },
        pageStyle: {
            type: Object,
            default: null,
        },
    },
    data () {
        return {
            dataList: [],
            codeNode: {},
            itemStyle: {
                width: '240px',
                height: '273px',
                margin: '12px',
            },
            tipStyle: {
                display: 'block',
                margin: '10px 0',
                textAlign: 'center',
                width: '250px',
                fontSize: '12px',
            },
        };
    },
    computed: {
        containerStyle () {
            let style = this.pageStyle || {};
            style.fontSize = 0;
            if (this.pageSize) {
                style.width = this.pageSize === 'portrait' ? '210mm' : '297mm';
                style.height = this.pageSize === 'portrait' ? '297mm' : '210mm';
            }
            return style;
        },
    },
    watch: {
        data: {
            handler () {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        init () {
            const _this = this;
            if (!_this.data) {
                return;
            }
            _this.dataList = _this.data.map(item => $.extend({}, item));
            this.$nextTick(() => {
                _this.initQrCode();
            });
        },
        initQrCode () {
            const _this = this;
            let codeNode = {};
            this.dataList.forEach(item => {
                let container = _this.$refs[`qrcode_${item.sid}`][0];
                $(container).empty();
                codeNode[item.sid] = new QRCode(container, {
                    text: item.text,
                    width: _this.size,
                    height: _this.size,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H,
                });
            });
            _this.codeNode = codeNode;
        },
        download () {
            if (this.dataList.length === 1) {
                const nodeList = Array.prototype.slice.call(this.codeNode[this.dataList[0].sid]._el.children);
                const img = nodeList.find((item) => item.nodeName.toUpperCase() === 'IMG');
                // 构建画布
                let canvas = document.createElement('canvas');
                canvas.width = img.width;
                canvas.height = img.height;
                canvas.getContext('2d').drawImage(img, 0, 0);
                // 构造url
                let imgURL = canvas.toDataURL('image/png');
                let a = document.createElement("a");
                let ua = navigator.userAgent;
                if (ua.indexOf("Trident") !== - 1 && ua.indexOf("Windows") !== - 1) {
                    // IE内核 并且  windows系统 情况下 才执行;
                    let bstr = atob(imgURL.split(",")[1]);
                    let n = bstr.length;
                    let u8arr = new Uint8Array(n);
                    while (n --) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    let blob = new Blob([u8arr]);
                    window.navigator.msSaveOrOpenBlob(blob, "二维码" + "." + "png");
                } else if (ua.indexOf("Firefox") > - 1) {
                    //火狐兼容下载
                    let blob = this.base64ToBlob(imgURL); //new Blob([content]);
                    let evt = document.createEvent("HTMLEvents");
                    evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
                    a.download = " "; //下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
                    a.href = URL.createObjectURL(blob);
                    a.dispatchEvent(
                        new MouseEvent("click", {
                            bubbles: true,
                            cancelable: true,
                            view: window,
                        })
                    ); //兼容火狐
                } else {
                    //谷歌兼容下载
                    img.src = canvas.toDataURL("image/jpg");
                    a.href = img.src;
                    //设置下载文件的名字
                    a.download = "二维码";
                    //点击
                    a.click();
                }
            }
        },
        //base64转blob
        base64ToBlob (code) {
            let parts = code.split(";base64,");
            let contentType = parts[0].split(":")[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;
            let uInt8Array = new Uint8Array(rawLength);
            for (let i = 0; i < rawLength; ++ i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], {type: contentType});
        },

        doPrint () {
            let printTemplate = new hiprint.PrintTemplate();
            printTemplate.printByHtml($(this.$el).html());
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.qrcode_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    overflow-y: auto;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
}
</style>
